﻿using Newtonsoft.Json.Linq;
using ProjectStatic.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ProjectStatic.Models
{
    public class ProjectInsertService
    {
        public ProjectInsertService()
        {
            this.Items = new List<ProjectItemLog>();
            
        }
        public ProjectLog Log { get; set; }
        public List<ProjectItemLog> Items { get; set; }


        public int ReadJsonAndSave(string TeamLeaderName, JToken item)
        {
            ProjectLog log = new ProjectLog()
            {
                Date = item["Date"].ToString(),
                Points = item["Points"].ToObject<double>(),
                PrjId = item["PrjId"].ToString(),
                TeamLeader = TeamLeaderName
            };
            this.Log = log;
            var logitems = item["Items"].ToObject<JArray>();
            string prjItemLog_TableName = log.PrjId;

            foreach (var logitem in logitems)
            {
                //itemName  points
                ProjectItemLog prjItemLog = new ProjectItemLog()
                {
                    Date = item["Date"].ToString(),
                    ItemName = logitem["itemName"].ToString(),
                    Points = logitem["points"].ToObject<double>()
                };
                if (prjItemLog.Points > 0)
                {
                    Items.Add(prjItemLog);
                }
            }
            return SaveIntoDatabase();
        }

        private int SaveIntoDatabase()
        {
            string sql = "";
            List<string> list = new List<string>();

            sql = string.Format("delete from [{0}] where 日期='{1}' and 班组长='{2}' and 项目编号='{3}'", 
                "projectlog", this.Log.Date,this.Log.TeamLeader,this.Log.PrjId);
            list.Add(sql);
            list.Add(Log.GenerateInsertSqlStr());

            if (!DbHelperSQL.TabExists(this.Log.PrjId))
            {
                sql = string.Format("select *  into [{0}] from project_template", this.Log.PrjId);
                list.Add(sql);
            }

            sql = string.Format("delete from [{0}] where 日期='{1}'", Log.PrjId, Log.Date);
            list.Add(sql);
            foreach (var item in Items)
            {
                list.Add(item.GenerateInsertSqlStr(Log.PrjId));
            }
            return DbHelperSQL.ExecuteSqlTran(list);
        }
    }
}